package com.zhangsun.newMvvm.common.network.exception;

import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.zhangsun.newMvvm.base.bean.ResponseData;
import com.zhangsun.newMvvm.common.tools.GsonTool;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.ResponseBody;
import retrofit2.HttpException;
import retrofit2.Response;

public class ExceptionEngine {

    public static ApiException handleException(Throwable e) {
        ResponseData responseData;
        if (e instanceof HttpException) {             //HTTP 错误
            HttpException httpException = (HttpException) e;
            Response response = httpException.response();
            try {
                ResponseBody bady = response.errorBody();
                if (bady != null) {
                    responseData = GsonTool.getObject(bady.string(), ResponseData.class);
                } else {
                    responseData = new ResponseData<>();
                    responseData.setCode("system_error");
                    responseData.setMessage("系统异常");
                }
            } catch (Exception e1) {
                responseData = new ResponseData<>();
                responseData.setCode("system_error");
                responseData.setMessage("系统异常：" + e1.toString());
            }
        } else if (e instanceof ConnectException || e instanceof SocketTimeoutException) {
            /*链接异常*/
            responseData = new ResponseData<>();
            responseData.setCode("time_out");
            responseData.setMessage("请检查网络链接");
        } else if (e instanceof JsonIOException || e instanceof JsonSyntaxException) {
            /*解析异常*/
            responseData = new ResponseData<>();
            responseData.setCode("json_syntax");
            responseData.setMessage("解析异常");
        } else if (e instanceof UnknownHostException) {
            /*无法解析该域名异常*/
            responseData = new ResponseData<>();
            responseData.setCode("unknown_host");
            responseData.setMessage("无法解析该域名异常");
        } else {
            /*未知异常*/
            responseData = new ResponseData<>();
            responseData.setCode("unknown_error");
            responseData.setMessage("未知异常：" + e.getMessage());
        }
        return new ApiException(e, responseData.getCode(), responseData.getMessage());
    }

}
